package com.itump.base.util;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import com.itump.base.util.PropertiesReader;
import com.itump.base.util.Utils;
/** 
 * <p> 功能描述: 发送外网邮件</p>
 * <p> 创建时间：2011-07-17 </p>
 * <p> 版本信息：1.0 </p>
 * <p> Copyright: Copyright (c) 2009 </p>
 
 */
public class SendMail {
	private MimeMessage mimeMsg; // MIME邮件对象
	private Session session; // 邮件会话对象
	private Properties props; // 系统属性
//	private boolean needAuth = false; // smtp是否需要认证
	private String username = ""; // smtp认证用户名和密码
	private String password = "";
	static PropertiesReader property = PropertiesReader.getIntance();
	private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

	public SendMail() {
		setSmtpHost(property.getProperty("smtp.hostname_w"));// 如果没有指定邮件服务器,就从getConfig类中获取
		createMimeMessage();
	}

	public SendMail(String smtp) {
		setSmtpHost(smtp);
		createMimeMessage();
	}

	public void setSmtpHost(String hostName) {
		System.out.println("设置系统属性：mail.smtp.host = " + hostName);
		if (props == null)
			props = System.getProperties(); // 获得系统属性对象
		props.put("mail.smtp.host", hostName); // 设置SMTP主机
	}

	public boolean createMimeMessage()
	{
		try {
			System.out.println("准备获取邮件会话对象！");
			session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
		}
		catch (Exception e) {
			System.err.println("获取邮件会话对象时发生错误！" + e);
			return false;
		}
		System.out.println("准备创建MIME邮件对象！");
		try {
			mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
			mp = new MimeMultipart();
			return true;
		}
		catch (Exception e) {
			System.err.println("创建MIME邮件对象失败！" + e);
			return false;
		}
	}
	/**
	 * 功能:发送邮件给该用户
	 * @param title    邮件主题
	 * @param content  邮件内容
	 * @param to  接收人邮件地址
	 * @param cc  抄送人邮件地址
	 * @param filenameURL   附件地址
	 */
	public void sendMail(String title,String content,String to,String cc,String filenameURL) {
		try {		
			//设置smtp身份认证:
			if (props == null)props = System.getProperties();
			props.put("mail.smtp.auth", "true");
            //设置收件人
			InternetAddress toAddress[] = this.getAddress(to);
            if (to != null)
            //mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            mimeMsg.setRecipients(Message.RecipientType.TO, toAddress);
           //设置抄送人
            InternetAddress ccAddress[] = this.getAddress(cc);
            if (cc != null)
            mimeMsg.setRecipients(Message.RecipientType.CC,ccAddress);
           //设置发信人
            String from  = property.getProperty("smtp.email_w");
            mimeMsg.setFrom(new InternetAddress(from));
           //设置邮件主题
			mimeMsg.setSubject(title,"GBK");	
		   //设置邮件内容
			BodyPart bp = new MimeBodyPart();
            bp.setContent("" + content, "text/html;charset=GB2312");
            mp.addBodyPart(bp);
		  //增加邮件附件
            if (!"".equals(filenameURL) ) {
	            BodyPart bpt = new MimeBodyPart();
	            FileDataSource fileds = new FileDataSource(filenameURL);
	            bpt.setDataHandler(new DataHandler(fileds));
	            bpt.setFileName(fileds.getName());
	            mp.addBodyPart(bpt);
            }
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			System.out.println("正在发送邮件....");
			//发送	
			Session mailSession = Session.getInstance(props, null);
			Transport transport = mailSession.getTransport("smtp");
			username = property.getProperty("smtp.username_w");
			password = property.getProperty("smtp.password_w");
			transport.connect((String) props.get(property.getProperty("smtp.hostname_w")), username, password);
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
			//transport.send(mimeMsg);
			System.out.println("发送邮件成功！");
			transport.close();
			}catch (Exception e)
			{
				System.err.println("邮件发送失败！" + e);

			}
		}
	public void setNeedAuth(boolean need) {
		System.out.println("设置smtp身份认证：mail.smtp.auth = " + need);
		if (props == null)
			props = System.getProperties();
		if (need) {
			props.put("mail.smtp.auth", "true");
		} else {
			props.put("mail.smtp.auth", "false");
		}
	}

	public void setNamePass(String name, String pass) {
		username = name;
		password = pass;
	}

	public boolean setSubject(String mailSubject) {
		System.out.println("设置邮件主题！");
		try {
			mimeMsg.setSubject(mailSubject);
			return true;
		}
		catch (Exception e) {
			System.err.println("设置邮件主题发生错误！");
			return false;
		}
	}

	public boolean setBody(String mailBody) {
		try {
			BodyPart bp = new MimeBodyPart();
			bp.setContent("" + mailBody, "text/html;charset=GB2312");
			mp.addBodyPart(bp);
			return true;
		}
		catch (Exception e) {
			System.err.println("设置邮件正文时发生错误！" + e);
			return false;
		}
	}

	public boolean addFileAffix(String filename) {
		System.out.println("增加邮件附件：" + filename);
		try {
			BodyPart bp = new MimeBodyPart();
			FileDataSource fileds = new FileDataSource(filename);
			bp.setDataHandler(new DataHandler(fileds));
			bp.setFileName(fileds.getName());
			mp.addBodyPart(bp);
			return true;
		}
		catch (Exception e) {
			System.err.println("增加邮件附件：" + filename + "发生错误！" + e);
			return false;
		}
	}

	public boolean setFrom(String from) {
		System.out.println("设置发信人！");
		try {
			mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public boolean setTo(String to) {
		if (to == null)
			return false;
		try {
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
					.parse(to));
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public boolean setCopyTo(String copyto)
	{
		if (copyto == null)
			return false;
		try {
			mimeMsg.setRecipients(Message.RecipientType.CC,
					(Address[]) InternetAddress.parse(copyto));
			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	public boolean sendout()
	{
		try {
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
			System.out.println("正在发送邮件....");
			Session mailSession = Session.getInstance(props, null);
			Transport transport = mailSession.getTransport("smtp");
			transport.connect((String) props.get(property
					.getProperty("smtp.hostname_w")), username, password);
			transport.sendMessage(mimeMsg, mimeMsg
					.getRecipients(Message.RecipientType.TO));
			// transport.send(mimeMsg);
			System.out.println("发送邮件成功！");
			transport.close();
			return true;
		}
		catch (Exception e)
		{
			System.err.println("邮件发送失败！" + e);
			return false;
		}
	}

	public String mailContent() {
		String mailContent = "";
		mailContent="你好！\n\n";
		mailContent += "\t邮件正文\n\n";
		mailContent += "\t这是一个测试邮件发送和接收的邮件！请到http://b2b.cgnpc.com.cn 下查看待处理的文件！";
		mailContent += "\t---------------------------------------------------------------";
		return mailContent;
	}

	private InternetAddress[] getAddress(String address)throws AddressException {
     try {
		String[] addresss = Utils.strToArr(address, ";");
		if (addresss == null || addresss.length < 1)
			return null;
		else {
			InternetAddress[] ia = new InternetAddress[addresss.length];
			for (int i = 0; i < addresss.length; i++) {
	
				ia[i] = new InternetAddress(addresss[i]);
			}
			return ia;
		}
	} catch (Exception e) {
		return null;
	}
}
	/**
	 * 发送邮件功能
	 * @param args
	 */
	public static void main(String args[])
    {      
        try 
        {  
//        	String procName="";
        	String mailContent="质保系统";
        	String email="yangyong00001@126.com";
        	SendMail themail=new SendMail();  
        	/**
			themail.setNeedAuth(true);
			if (themail.setSubject(procName) == false)return;
			if (themail.setBody(mailContent) == false)return;
			if (themail.setTo(email) == false)return;
			if (themail.setFrom(property.getProperty("smtp.email_w")) == false)return;
			themail.setNamePass(property.getProperty("smtp.username_w"), property.getProperty("smtp.password_w"));
			if (themail.sendout() == false)return;
			**/
			themail.sendMail("质保系统附件提醒", mailContent, email,null, "");
        }
        catch(Exception ex){
        	ex.printStackTrace();
        }
    }
  

}